package com.sunwayhorizo.health.business.clinic.consultation;

import java.text.*;
import java.util.*;
import javax.ejb.*;
import org.jboss.seam.*;
import org.jboss.seam.annotations.*;
import com.sunwayhorizo.health.business.base.*;
import com.sunwayhorizo.health.business.clinic.consultation.query.*;
import com.sunwayhorizo.health.business.dto.*;
import com.sunwayhorizo.health.business.dto.clinic.consultation.*;
import com.sunwayhorizo.health.business.integration.securityI.SecurityInterfaceWrapManagerLocal;
import com.sunwayhorizo.health.business.patad.empi.query.*;
import com.sunwayhorizo.health.business.registries.employee.query.*;
import com.sunwayhorizo.health.business.registries.organization.query.*;
import com.sunwayhorizo.health.common.*;
import com.sunwayhorizo.health.common.validateGroups.*;
import com.sunwayhorizo.health.hl7.common.*;
import com.sunwayhorizo.health.hl7.factories.*;
import com.sunwayhorizo.health.hl7.rim.*;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.rim.Rolelink;
import com.sunwayhorizo.health.hl7.vocabulary.*;

@Stateless
@Name("ConsultationManager")
public class ConsultationManager extends BaseManager implements ConsultationManagerLocal
{
    private DepartmentQueryLocal departmentQuery = (DepartmentQueryLocal) Component.getInstance("DepartmentQuery");

    private PatientQueryLocal patientQuery = (PatientQueryLocal) Component.getInstance("PatientQuery");
    private ConsultationQueryLocal consultationQuery = (ConsultationQueryLocal) Component.getInstance("ConsultationQuery");
    private ValidateUtilLocal validateUtil = (ValidateUtilLocal) Component.getInstance("ValidateUtil");
    private SecurityInterfaceWrapManagerLocal securityInterfaceWrapManager = (SecurityInterfaceWrapManagerLocal) Component
        .getInstance("SecurityInterfaceWrapManager");
    private EmployeeQueryLocal employeeQuery = (EmployeeQueryLocal) Component.getInstance("EmployeeQuery");


    // 新增会诊申请
    @Override
    public ResultsDTO newConsultation(ConsultationDTO dto) throws Hl7Exception, ParseException
    {

        ResultsDTO resultsDTO = validateNewConsultation(dto);
        if (resultsDTO != null)
        {
            log.info(resultsDTO.getResultDesc());
            return resultsDTO;
        }

        Observation obs = constructConsultation(dto);

        // 患者参与
        addPatient(dto);

        // 邀请与被邀请人参与
        addInviteRole(dto);

        ControlAct controlAct = newControlAct(obs);

        save(controlAct);
        log.info("ConsultationManager-newConsultation-创建会诊申请成功");
        return getResultsDTO("创建会诊申请成功", true, true);
    }


    // 删除会诊
    @Override
    public ResultsDTO deleteConsultation(String consultationId) throws Hl7Exception
    {
        List<ActParticipation> parts = consultationQuery.findParitcipationsByConsultationId(consultationId);
        if (!parts.isEmpty())
        {
            for (ActParticipation part : parts)
            {
                em.remove(part);
            }
            em.flush();
            log.info("ConsultationManager-newConsultation-删除会诊申请成功!");
            return getResultsDTO("删除成功！", true, true);
        }
        else
        {
            log.info("ConsultationManager-newConsultation-根据id查询会诊申请失败，无法删除");
            return getResultsDTO("删除失败！", true, false);
        }
    }


    // 修改会诊
    @Override
    public ResultsDTO modifyConsultation(ConsultationDTO dto) throws Hl7Exception, ParseException
    {
        Observation obs = consultationQuery.findObservationByConsultationId(dto.getConsultationId());
        constructConsultation(obs, dto);
        update(obs);
        log.info("ConsultationManager-constructConsultation-修改会诊动作成功");
        return getResultsDTO("修改会诊动作成功", true, true);
    }


    // 查询科室会诊
    @Override
    public ResultsDTO findGroupConsultation(ConsultationDTO dto, PageDTO pageDTO) throws Hl7Exception
    {

        em.clear();
        ResultsDTO resultsDTO = validateFindConsultation(dto);
        if (resultsDTO != null)
        {
            log.info(resultsDTO.getResultDesc());
            return resultsDTO;
        }
        String typeCode = null;
        // 受邀
        if ("0".equals(dto.getTypeCode()))
        {
            typeCode = ParticipationType.COV.code().stringValue();
        }
        // 申请
        else if ("1".equals(dto.getTypeCode()))
        {
            typeCode = ParticipationType.LOC.code().stringValue();
        }

        Date from = DateUtil.getDateBy3String(dto.getFrom());
        Date to = DateUtil.getDateBy3String(dto.getTo());
        List<ActParticipation> consultations = consultationQuery.findObservationInGroup(dto.getWorkgroupId(), typeCode, dto.getStatusCode(), from, to,
            pageDTO.getPageSize(), pageDTO.getPageNo());
        List<ConsultationDTO> dtos = new ArrayList<ConsultationDTO>();

        for (ActParticipation part : consultations)
        {
            convertConsultation(part, dtos);
        }
        // log.info(dtos);
        pageDTO.setTotalRecord((int) consultationQuery.findCountObservationInGroup(dto.getWorkgroupId(), typeCode, dto.getStatusCode(), from, to));
        return getResultsDTO("查询成功", true, dtos, pageDTO);
    }


    // 查询我的会诊
    @Override
    public ResultsDTO findMyConsultation(ConsultationDTO dto, PageDTO pageDTO) throws Hl7Exception
    {
        em.clear();
        // 验证
        ResultsDTO resultsDTO = validateFindConsultation(dto);
        if (resultsDTO != null)
        {
            log.info(resultsDTO.getResultDesc());
            return resultsDTO;
        }
        String typeCode = null;
        // 受邀
        if ("0".equals(dto.getTypeCode()))
        {
            typeCode = ParticipationType.PRCP.code().stringValue();

        }
        // 申请
        else if ("1".equals(dto.getTypeCode()))
        {
            typeCode = ParticipationType.AUT.code().stringValue();
        }
        Date from = DateUtil.getDateBy3String(dto.getFrom());
        Date to = DateUtil.getDateBy3String(dto.getTo());
        List<ActParticipation> consultations = consultationQuery.findMyObservation(dto.getEmployeeId(), typeCode, dto.getStatusCode(), from, to,
            pageDTO.getPageSize(), pageDTO.getPageNo());
        List<ConsultationDTO> dtos = new ArrayList<ConsultationDTO>();

        for (ActParticipation obs : consultations)
        {
            convertMyConsultation(obs, dtos);
        }
        pageDTO.setTotalRecord((int) consultationQuery.findCountMyObservation(dto.getEmployeeId(), typeCode, dto.getStatusCode(), from, to));
        return getResultsDTO("查询成功", true, dtos, pageDTO);
    }


    // 组装我的会诊
    private List<ConsultationDTO> convertMyConsultation(ActParticipation part, List<ConsultationDTO> dtos) throws Hl7Exception
    {
        Observation obs = (Observation) part.getParticipationAct();
        // 如果是受邀人
        if (part.getTypecode().equals(ParticipationType.PRCP))
        {
            ConsultationDTO dto = new ConsultationDTO();
            convertConsultation(obs, dto);
            Employee emp = (Employee) part.getRole();
            dto.setTypeCode("0");

            dto.getInviteInfo().setEmployeeId(emp.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
            dto.getInviteInfo().setEmployeeName(emp.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
            for (ActParticipation part1 : obs.getParticipations())
            {
                // 患者
                if (part1.getTypecode().equals(ParticipationType.SBJ))
                {
                    Patient patient = (Patient) part1.getRole();
                    dto.setHospitalizationNO(patient.getId(RoleIICode.ADMISSIONNO).extension().stringValue());
                    dto.setPatientId(patient.getId(RoleIICode.PATIENTID).extension().stringValue());
                    dto.setPatientName(patient.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
                // 会诊发起人
                else if (part1.getTypecode().equals(ParticipationType.AUT))
                {
                    Employee starter = (Employee) part1.getRole();
                    dto.setInviterId(starter.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
                    dto.setInviterName(starter.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
                // 会诊发起人所在工作组
                else if (part1.getTypecode().equals(ParticipationType.LOC))
                {
                    Role startWorkgroup = part1.getRole();
                    dto.setInviterWorkgroupId(startWorkgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
                    dto.setInviterWorkgroupName(startWorkgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
                // 会诊受邀工作组
                else if (part1.getTypecode().equals(ParticipationType.COV) && part1.getSignatureCode().code().equals(part.getSignatureCode().code()))
                {
                    Role workgroup = part1.getRole();
                    if (part1.getStatCode() != null)
                    {
                        dto.getInviteInfo().setStatusCode(part1.getStatCode().code().stringValue());
                    }
                    else
                    {
                        dto.getInviteInfo().setStatusCode(ParticipationStatus.UNACCEPT.code().stringValue());
                    }
                    // 会诊单号
                    dto.setConsultationId(part1.getSignatureCode().code().stringValue());
                    dto.getInviteInfo().setWorkgroupId(workgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
                    dto.getInviteInfo().setWorkgroupName(workgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
            }
            dtos.add(dto);
        }
        // 如果是申请人
        else if (part.getTypecode().equals(ParticipationType.AUT))
        {

            Employee starter = (Employee) part.getRole();
            for (ActParticipation part2 : obs.getParticipations())
            {
                // 受邀工作组
                if (part2.getTypecode().equals(ParticipationType.COV))
                {
                    ConsultationDTO dto = new ConsultationDTO();
                    dto.setTypeCode("1");
                    convertConsultation(obs, dto);
                    Role workgroup = part2.getRole();
                    if (part2.getStatCode() != null)
                    {
                        dto.getInviteInfo().setStatusCode(part2.getStatCode().code().stringValue());
                    }
                    else
                    {
                        dto.getInviteInfo().setStatusCode(ParticipationStatus.UNACCEPT.code().stringValue());
                    }
                    dto.getInviteInfo().setWorkgroupId(workgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
                    dto.getInviteInfo().setWorkgroupName(workgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                    // 会诊单号
                    dto.setConsultationId(part2.getSignatureCode().code().stringValue());
                    for (ActParticipation part3 : obs.getParticipations())
                    {
                        // 患者
                        if (part3.getTypecode().equals(ParticipationType.SBJ))
                        {
                            Patient patient = (Patient) part3.getRole();
                            dto.setHospitalizationNO(patient.getId(RoleIICode.ADMISSIONNO).extension().stringValue());
                            dto.setPatientId(patient.getId(RoleIICode.PATIENTID).extension().stringValue());
                            dto.setPatientName(patient.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                        }
                        // 会诊申请人工作组
                        else if (part3.getTypecode().equals(ParticipationType.LOC))
                        {
                            Role starterworkgroup = part3.getRole();
                            dto.setInviterWorkgroupId(starterworkgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
                            dto.setInviterWorkgroupName(starterworkgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                        }
                        // 会诊受邀人
                        else if (part3.getTypecode().equals(ParticipationType.PRCP)
                                && part3.getSignatureCode().code().equals(part2.getSignatureCode().code()))
                        {
                            Employee emp = (Employee) part3.getRole();
                            dto.getInviteInfo().setEmployeeId(emp.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
                            dto.getInviteInfo().setEmployeeName(emp.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                        }
                    }
                    dto.setInviterId(starter.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
                    dto.setInviterName(starter.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                    dtos.add(dto);
                }
            }
        }
        return dtos;

    }


    // 接受会诊
    @Override
    public ResultsDTO acceptConsultation(String accountName, String password, ConsultationDTO dto) throws Hl7Exception
    {
        em.clear();
        // 根据用户名密码查询关联员工号
        String emplyeeId = securityInterfaceWrapManager.findEmpCodeByAccount(accountName, password);
        if (StrUtil.isEmpty(emplyeeId))
        {
            log.info("查询账号关联员工号为空！");
            return getResultsDTO("账号状态有误，请检查用户名，密码及关联员工！", true, false);
        }
        String workgroupId = dto.getInviteInfo().getWorkgroupId();
        Role workgroup = departmentQuery.findWorkGroupRoleByWorkGroupCode(workgroupId);
        Employee emp = employeeQuery.findEmployeeByCode(emplyeeId);

        if (workgroup == null || emp == null)
        {
            log.info("员工或工作组为空！");
            return getResultsDTO("员工或工作组为空！", true, false);
        }
        // 判断是否为该工作组员工签到
        boolean isInWorkgroup = false;
        for (Rolelink link : emp.getSourceRolelinks())
        {
            if (link.getTargetRole().getRoleId().equals(workgroup.getRoleId()))
            {
                isInWorkgroup = true;
                break;
            }
        }
        if (!isInWorkgroup)
        {
            log.info("非该科室员工签到！");
            return getResultsDTO("非该科室员工签到！", true, false);
        }
        String consultationId = dto.getConsultationId();

        boolean hasEmp = false;

        List<ActParticipation> parts = consultationQuery.findParitcipationsByConsultationId(consultationId);
        Observation obs = null;
        for (ActParticipation part : parts)
        {

            if (!ParticipationStatus.ACCEPT.equals(part.getStatCode()))
            {
                part.setStatCode(ParticipationStatus.ACCEPT);
                part.setTime(DataTypeUtil.getIVL_TS(new Date(), new Date()));

                if (part.getTypecode().equals(ParticipationType.COV))
                {
                    log.info("修改工作组受邀状态为接受");
                    obs = (Observation) part.getParticipationAct();
                }
                else if (part.getTypecode().equals(ParticipationType.PRCP))
                {
                    hasEmp = true;
                    part.setRoleparticipation(emp);
                    log.info("修改受邀人状态为接受");
                }
                em.merge(part);
            }
            else
            {
                log.info("ConsultationManager-acceptConsultation-已经接受邀请,接受失败！");
                return getResultsDTO("已经接受邀请,接受失败！", true, false);
            }

        }

        // 没有默认邀请则新建
        if (!hasEmp)
        {
            ActParticipation empPart = ActFactory.getInstance().newActParticipation();
            empPart.setTypeCode(ParticipationType.PRCP);
            empPart.setSignatureCode(DataTypeUtil.getCE(consultationId));
            empPart.setRoleparticipation(emp);
            empPart.setStatCode(ParticipationStatus.ACCEPT);
            empPart.setParticipationAct(obs);
            em.persist(empPart);
            log.info("新建受邀人状态为接受");
        }
        em.flush();
        em.clear();
        log.info("接受邀请成功");
        return getResultsDTO("接受邀请成功！", true, true);
    }


    // 组装会诊动作
    private ConsultationDTO convertConsultation(Observation obs, ConsultationDTO dto) throws Hl7Exception
    {
        // 申请时间
        dto.setApplicationDate(obs.getAvailabilityTime().toDateString("yyyy-MM-dd HH:mm:ss"));
        // 诊断
        dto.setDiagnosis(obs.getInterpretationCode().code().stringValue());
        // 等级
        if (obs.getLevelCode() != null)
        {
            dto.setLevel(obs.getLevelCode().code().stringValue());
        }
        // 请到时间
        dto.setConfirmDate(obs.getActivityTime().hull().low().toDateString("yyyy-MM-dd HH:mm:ss"));
        // 诊断
        dto.setDiagnosis(obs.getInterpretationCode().code().stringValue());
        // 病史
        dto.setMedicalHistory(obs.getMedicalHistory().code().stringValue());
        // 体征
        dto.setPhysicalSign(obs.getPhysicalSign().code().stringValue());
        // 相关实验，特殊检查材料
        dto.setMedicalData(obs.getMedicalHistory().code().stringValue());
        // 会诊目的及要求
        dto.setPurpose(obs.getPurposeCode().code().stringValue());
        return dto;
    }


    // 组装科室会诊信息
    private List<ConsultationDTO> convertConsultation(ActParticipation part, List<ConsultationDTO> dtos) throws Hl7Exception
    {
        Observation obs = (Observation) part.getParticipationAct();
        // 如果是受邀科室
        if (part.getTypecode().equals(ParticipationType.COV))
        {
            ConsultationDTO dto = new ConsultationDTO();
            // 组装会诊动作
            convertConsultation(obs, dto);
            // 得到受邀科室
            Role workgroup = part.getRole();
            // 判定类型为受邀
            dto.setTypeCode("0");
            // 获取受邀状态（接受还是未接受）
            if (part.getStatCode() != null)
            {
                dto.getInviteInfo().setStatusCode(part.getStatCode().code().stringValue());
            }
            else
            {
                dto.getInviteInfo().setStatusCode("0");
            }
            // 受邀信息工作组id
            dto.getInviteInfo().setWorkgroupId(workgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
            // 受邀信息工作组name
            dto.getInviteInfo().setWorkgroupName(workgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
            // 会诊单号
            dto.setConsultationId(part.getSignatureCode().code().stringValue());
            // 遍历其他参与角色
            for (ActParticipation part1 : obs.getParticipations())
            {
                // 患者
                if (part1.getTypecode().equals(ParticipationType.SBJ))
                {
                    Patient patient = (Patient) part1.getRole();
                    dto.setHospitalizationNO(patient.getId(RoleIICode.ADMISSIONNO).extension().stringValue());
                    dto.setPatientId(patient.getId(RoleIICode.PATIENTID).extension().stringValue());
                    dto.setPatientName(patient.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
                // 会诊发起人
                else if (part1.getTypecode().equals(ParticipationType.AUT))
                {
                    Employee emp = (Employee) part1.getRole();
                    dto.setInviterId(emp.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
                    dto.setInviterName(emp.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
                // 会诊发起人所在工作组
                else if (part1.getTypecode().equals(ParticipationType.LOC))
                {
                    Role startWorkgroup = part1.getRole();
                    dto.setInviterWorkgroupId(startWorkgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
                    dto.setInviterWorkgroupName(startWorkgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
                // 会诊受邀人
                else if (part1.getTypecode().equals(ParticipationType.PRCP) && part1.getSignatureCode().code().equals(part.getSignatureCode().code()))
                {
                    Employee emp = (Employee) part1.getRole();
                    dto.getInviteInfo().setEmployeeId(emp.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
                    dto.getInviteInfo().setEmployeeName(emp.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                }
            }
            dtos.add(dto);
        }
        // 如果是申请科室
        else if (part.getTypecode().equals(ParticipationType.LOC))
        {
            // 获取申请科室
            Role startWorkgroup = part.getRole();
            for (ActParticipation part2 : obs.getParticipations())
            {
                // 受邀工作组
                if (part2.getTypecode().equals(ParticipationType.COV))
                {
                    ConsultationDTO dto = new ConsultationDTO();
                    // 判定会诊类型为申请
                    dto.setTypeCode("1");
                    // 组装会诊动作
                    convertConsultation(obs, dto);
                    // 获取受邀工作组
                    Role workgroup = part2.getRole();
                    // 获取受邀状态（接受还是未接受）
                    if (part2.getStatCode() != null)
                    {
                        dto.getInviteInfo().setStatusCode(part2.getStatCode().code().stringValue());
                    }
                    else
                    {
                        dto.getInviteInfo().setStatusCode("0");
                    }
                    dto.getInviteInfo().setWorkgroupId(workgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
                    dto.getInviteInfo().setWorkgroupName(workgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                    // 会诊单号
                    dto.setConsultationId(part2.getSignatureCode().code().stringValue());

                    // 遍历其他参与角色
                    for (ActParticipation part3 : obs.getParticipations())
                    {
                        // 患者
                        if (part3.getTypecode().equals(ParticipationType.SBJ))
                        {
                            Patient patient = (Patient) part3.getRole();
                            dto.setHospitalizationNO(patient.getId(RoleIICode.ADMISSIONNO).extension().stringValue());
                            dto.setPatientId(patient.getId(RoleIICode.PATIENTID).extension().stringValue());
                            dto.setPatientName(patient.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                        }
                        // 会诊发起人
                        else if (part3.getTypecode().equals(ParticipationType.AUT))
                        {
                            Employee emp = (Employee) part3.getRole();
                            dto.setInviterId(emp.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
                            dto.setInviterName(emp.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                        }
                        // 会诊受邀人
                        else if (part3.getTypecode().equals(ParticipationType.PRCP)
                                && part3.getSignatureCode().code().equals(part2.getSignatureCode().code()))
                        {
                            Employee emp = (Employee) part3.getRole();
                            dto.getInviteInfo().setEmployeeId(emp.getId(RoleIICode.EMPLOYEEID).extension().stringValue());
                            dto.getInviteInfo().setEmployeeName(emp.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                        }
                    }
                    dto.setInviterWorkgroupId(startWorkgroup.getId(RoleIICode.DEPTCODE).extension().stringValue());
                    dto.setInviterWorkgroupName(startWorkgroup.getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().stringValue());
                    dtos.add(dto);
                }
            }
        }
        return dtos;
    }


    // 增加邀请角色
    private void addInviteRole(ConsultationDTO dto) throws Hl7Exception
    {
        // 申请人
        Employee inviter = employeeQuery.findEmployeeByCode(dto.getInviterId());
        // 申请工作组
        Role inviterWorkgroup = departmentQuery.findWorkGroupRoleByWorkGroupCode(dto.getInviterWorkgroupId());
        // 申请人角色参与
        ActParticipation part0 = ActFactory.getInstance().newActParticipation();
        part0.setTypeCode(ParticipationType.AUT);
        addParticipation(inviter, part0);
        // 申请工作组角色参与
        ActParticipation part3 = ActFactory.getInstance().newActParticipation();
        part3.setTypeCode(ParticipationType.LOC);
        addParticipation(inviterWorkgroup, part3);
        long i = 0l;
        for (InviteInfoDTO inviteInfo : dto.getInviteInfos())
        {
            i = i + 1;
            String consultationId = DateUtil.getNow() + dto.getHospitalizationNO() + i;

            // 被邀请工作组
            Role workgroup = departmentQuery.findWorkGroupRoleByWorkGroupCode(inviteInfo.getWorkgroupId());
            // 被邀请工作组参与
            ActParticipation part1 = ActFactory.getInstance().newActParticipation();
            part1.setTypeCode(ParticipationType.COV);
            part1.setStatCode(ParticipationStatus.UNACCEPT);
            part1.setSignatureCode(DataTypeUtil.getCE(consultationId));
            addParticipation(workgroup, part1);

            // 被邀请人
            if (StrUtil.isNotEmpty(inviteInfo.getEmployeeId()))
            {
                Employee emp = employeeQuery.findEmployeeByCode(inviteInfo.getEmployeeId());
                // 被邀请人参与
                ActParticipation part2 = ActFactory.getInstance().newActParticipation();
                part2.setTypeCode(ParticipationType.PRCP);
                part2.setStatCode(ParticipationStatus.UNACCEPT);
                part2.setSignatureCode(DataTypeUtil.getCE(consultationId));
                addParticipation(emp, part2);
            }

        }

    }


    // 患者参与会诊
    private void addPatient(ConsultationDTO dto) throws Hl7Exception
    {
        Patient pat = patientQuery.findPatientByNeturalId(dto.getPatientId());
        ActParticipation part0 = ActFactory.getInstance().newActParticipation();
        part0.setTypeCode(ParticipationType.SBJ);
        addParticipation(pat, part0);
    }


    // 构建会诊动作
    private Observation constructConsultation(Observation obs, ConsultationDTO dto) throws Hl7Exception, ParseException
    {
        // 申请时间
        obs.setAvailabilityTime(DataTypeUtil.getTS(dto.getApplicationDate()));
        // 请到时间
        obs.setActivityTime(DataTypeUtil.getGTS(DataTypeUtil.getIVL_TS(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dto.getConfirmDate()),
            new Date())));
        // 会诊等级
        obs.setLevelCode(DataTypeUtil.getCE(dto.getLevel()));
        // 诊断
        obs.setInterpretationCode(DataTypeUtil.getCE(dto.getDiagnosis()));
        // 病史
        obs.setMedicalHistory(DataTypeUtil.getCE(dto.getMedicalHistory()));
        // 体征
        obs.setPhysicalSign(DataTypeUtil.getCE(dto.getPhysicalSign()));
        // 相关实验，特殊检查材料
        obs.setMedicalData(DataTypeUtil.getCE(dto.getMedicalData()));
        // 会诊目的及要求
        obs.setPurposeCode(DataTypeUtil.getCE(dto.getPurpose()));

        return obs;
    }


    // 构建会诊
    private Observation constructConsultation(ConsultationDTO dto) throws Hl7Exception, ParseException
    {
        // 会诊申请单号
        // String consultationId = null;
        // if (StrUtil.isNotEmpty(dto.getConsultationId()))
        // {
        // consultationId = dto.getConsultationId();
        // }
        // else
        // {
        // consultationId = DateUtil.getNow() + dto.getHospitalizationNO()+;
        // }
        // II id = DataTypeUtil.getII(root, consultationId,
        // ActIICode.CONSULTATIONID.toString());
        // obs.setId(id);

        Observation obs = ActFactory.getInstance().newObservation(ActMood.APT, ActCode.CONSULTATION, null);

        obs.setStatusCode(ActStatus.ACTIVE);
        // 创建会诊动作
        constructConsultation(obs, dto);

        log.info("ConsultationManager-constructConsultation-构建会诊动作成功");
        return obs;
    }


    // 验证新建会诊单
    private ResultsDTO validateNewConsultation(ConsultationDTO dto)
    {
        ResultsDTO resultDTO = validateUtil.verifiedReturnResultsDTO(dto, NewConsultation.class);
        if (resultDTO != null)
        {
            log.info(resultDTO.getResultDesc());
        }
        return null;
    }


    // 验证查询会诊单
    private ResultsDTO validateFindConsultation(ConsultationDTO dto) throws Hl7Exception
    {
        ResultsDTO resultDTO = validateUtil.verifiedReturnResultsDTO(dto, FindConsultation.class);
        if (resultDTO != null)
        {
            log.info(resultDTO.getResultDesc());
            return resultDTO;
        }
        Role workgroup = departmentQuery.findWorkGroupRoleByWorkGroupCode(dto.getWorkgroupId());
        if (workgroup == null)
        {
            log.info("validateFindConsultation-当前工作组为空，不能查询！");
            return resultDTO;
        }
        return null;
    }

}
